package com.axter.libs.photo.previewphoto;

import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;

import com.axter.libs.photo.R;

import java.util.ArrayList;
import java.util.Collections;

/**
 * 预览图片
 * Created by axter on 2016/11/29.
 */

public class PreviewPhotoDeleteActivity extends PreviewPhotoBaseActivity {
    private ImageButton btn_left;
    private TextView tv_title;
    private ImageButton btn_right;
    /**
     * 图片地址坐标
     */
    private ArrayList<Integer> mPos;
    /**
     * 被删除图片地址坐标
     */
    private ArrayList<Integer> mDel;

    @Override
    protected void receiveIntentArgs() {
        super.receiveIntentArgs();

        if (mPaths != null && mPaths.size() > 0) {
            mPos = new ArrayList<>(mPaths.size());
            mDel = new ArrayList<>(mPaths.size());
            for (int i = 0, count = mPaths.size(); i < count; i++) {
                mPos.add(i);
            }
        }
    }

    @Override
    protected int getContentView() {
        return R.layout.previewphoto_mdelete;
    }

    @Override
    protected void initView() {
        super.initView();

        btn_left = (ImageButton) findViewById(R.id.btn_left);
        tv_title = (TextView) findViewById(R.id.tv_title);
        btn_right = (ImageButton) findViewById(R.id.btn_right);
        btn_left.setOnClickListener(this);
        btn_right.setOnClickListener(this);
    }

    @Override
    public void setPageText(int position) {
        tv_title.setText(position + 1 + "/" + getPagerCount());
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.btn_left) {
            finish();
        } else if (v.getId() == R.id.btn_right) {
            removePage();
        }
    }

    protected void removePage() {
        if (mPaths.size() == 1) {
            mPaths.remove(0);
            mAdapter.notifyDataSetChanged();

            mDel.add(mPos.get(0));
            mPos.remove(0);

            finishDelete();
        } else if (mCurrentIndex == mPaths.size() - 1) {
            int cur = mCurrentIndex;

            mAdapter.remove(cur);
            mDel.add(mPos.get(cur));
            mPos.remove(cur);

            if (mViewPager.getCurrentItem() == cur) {
                mViewPager.setCurrentItem(cur - 1, false);
            }
            setPageText(mCurrentIndex);
        } else {
            int cur = mCurrentIndex;

            mAdapter.remove(cur);
            mDel.add(mPos.get(cur));
            mPos.remove(cur);
            setPageText(mCurrentIndex);
        }
    }

    public void finishDelete() {
        if (mDel != null && mDel.size() > 0) {
            Collections.sort(mDel, Collections.reverseOrder());
            Intent intent = new Intent();
            intent.putIntegerArrayListExtra(EXTRA_OUT_DEL_POSITION, mDel);
            setResult(Activity.RESULT_OK, intent);
        }
        finish();
    }
}
